//
//  AppDelegate+AppService.m
//  YueYue
//
//  Created by hulu001 on 2023/5/20.
//

#import "AppDelegate+AppService.h"
#import <NIMSDK/NIMSDK.h>
#import <iflyMSC/iflyMSC.h>
#import <CL_ShanYanSDK/CL_ShanYanSDK.h>
#import "HLChatKit.h"
#import "HLCellLayoutConfig.h"
#import "HLCustomAttachmentDecoder.h"
#import "HLCustomNotificationCenter.h"
#import "HLRtcCallKit.h"
#import <CSVisitorSDK/CS53Manager.h>
#import <YTKNetwork/YTKNetwork.h>

#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import <libOpenInstallSDK/OpenInstallSDK.h>
#import "SJRotationManager.h"

#import "HLLoginViewController.h"
#import "HLNavigationController.h"

@interface AppDelegate (AppService) <NIMLoginManagerDelegate,OpenInstallDelegate>

@end

@implementation AppDelegate (AppService)


- (void)configWindowOptions:(NSDictionary *)launchOptions
{   
    [CLShanYanSDKManager initWithAppId:cl_SDK_APPID complete:nil];
    [[CS53Manager sharedManager] startWithAppId:CS53_APPID arg:CS53_ARG];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    [self.window makeKeyAndVisible];
    
    [SJRotationManager supportedInterfaceOrientationsForWindow:self.window];
    
    if (![[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"AppVersion"]]) {
        [[NSUserDefaults standardUserDefaults] setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"AppVersion"];
        [HLUIHelper setRootLogin];
    } else {
        HLLoginModel *login = [HLLoginModel dataWithKeychain];
        if (login == nil) {
            [HLHelper shanYanLoadWithCallback:^{
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [HLUIHelper setRootLogin];
                });
            }];
            [HLUIHelper setRootLaunch];
        } else {
            [NIMSDK.sharedSDK.loginManager autoLogin:login.userId token:login.yxToken];
            if (login.isInfoDone == NO) {
                [HLUIHelper setRootInfo];
            } else {
                [HLUIHelper setRootTabBar];
            }
        }
    }
}


- (void)configHTTP
{
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    config.baseUrl = HTTP_SEVER_URL;
    config.cdnUrl = HTTP_SEVER_URL;
}

- (void)configNIM
{
    NIMSDKConfig *config = [NIMSDKConfig sharedConfig];
    config.fetchAttachmentAutomaticallyAfterReceiving = NO; // 关闭自动下载附件
    config.shouldSyncStickTopSessionInfos   = YES;  // 开启置顶功能
    config.asyncLoadRecentSessionEnabled    = YES;  // 开启当大于1000条最近会话后，异步获取最近会话的功能
    config.fetchAttachmentAutomaticallyAfterReceiving = YES;
//    config.shouldConsiderRevokedMessageUnreadCount = YES;
    
    NIMServerSetting *setting    = [[NIMServerSetting alloc] init];
    setting.httpsEnabled = NO;
    [[NIMSDK sharedSDK] setServerSetting:setting];
    NIMSDKOption *option = [NIMSDKOption optionWithAppKey:NIM_Key];
    option.apnsCername = NIM_Cer_Name;
    [[NIMSDK sharedSDK] registerWithOption:option];
    [NIMSDK.sharedSDK.mediaManager switchAudioOutputDevice:NIMAudioOutputDeviceSpeaker];
    
    [NIMCustomObject registerCustomDecoder:[HLCustomAttachmentDecoder new]]; // 注册自定义消息解析器
    HLChatKit.shareSDK.cellConfig = [[HLCellLayoutConfig alloc] init];
    [NIMSDK.sharedSDK.loginManager addDelegate:self];
}

- (void)configRTCKit {
    HLRtcCallOptions *option = [HLRtcCallOptions new];
    [[HLRtcCallKit sharedInstance] setupAppKey:NIM_Key options:option];
    [[HLRtcCallKit sharedInstance] setTimeOutSeconds:30];
    [NERtcEngine.sharedEngine setExternalVideoSource:YES isScreen:NO];
    [HLCustomNotificationCenter registerCustomNotificationCanter];
}

- (void)configIfly
{
    //Appid是应用的身份信息，具有唯一性，初始化时必须要传入Appid。
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@", @"c13039a9"];
    IFlySpeechUtility *object = [IFlySpeechUtility createUtility:initString];
    if (object) {
        [QMUIConsole log:@"讯飞登陆成功"];
    }
    NSString *st = [IFlySetting getVersion];
    [QMUIConsole log:[NSString stringWithFormat:@"[IFLYSetting getVersion] = %@",st]] ;
}

- (void)configPlatforms
{
    [UMSocialGlobal shareInstance].universalLinkDic =@{@(UMSocialPlatformType_WechatSession):APP_UNIVERSAL_LINK};
    
    [UMConfigure initWithAppkey:@"6407e845d64e686139448d75" channel:@"App Store"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_APPID appSecret:WX_APPSecrect redirectURL:APP_UNIVERSAL_LINK];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:WX_APPID appSecret:WX_APPSecrect redirectURL:APP_UNIVERSAL_LINK];

}


- (void)configOpenInstall
{
    [OpenInstallSDK initWithDelegate:self];
}

- (BOOL)continueUserActivity:(NSUserActivity *)userActivity
{
    [OpenInstallSDK continueUserActivity:userActivity];
    
    NSURL *url = userActivity.webpageURL;
    
    return [[UMSocialManager defaultManager] handleUniversalLink:userActivity options:nil];
}

- (void)handLinkURL:(NSURL *)url
{
    [[UMSocialManager defaultManager] handleOpenURL:url];
    [OpenInstallSDK handLinkURL:url];
}

#pragma mark - 登录被T掉回调
- (void)onKickout:(NIMLoginKickoutResult *)result;
{
    //TODO: 退出、回到登陆页
    [HLHelper logout];
    [HLUIHelper setRootLogin];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [QMUITips showWithText:@"账号已在其他设备登录，请重新登录"];
    });
}

@end
